import PropTypes from "prop-types"
import React, { memo, useState } from "react"

import { FilterWrapper } from "./style"
import fliterData from "@/assets/data/filter_data.json"
import classNames from "classnames"

const EntireFilter = memo((props) => {
  const [selectItem, setSelectItem] = useState([])
  function itemClick(item) {
    const newItem = [...selectItem]
    
    if(newItem.includes(item)) {
      // 再次点击则删除 该item
      // 通过 findIndex 找到对应的索引,再用 splice 删除
      const itemIndex = newItem.findIndex(fliterItem => fliterItem === item)
      newItem.splice(itemIndex, 1)
    } else {
      newItem.push(item)
    }
    setSelectItem(newItem)
  }
  return (
    <FilterWrapper>
      <div className="filter">
        {fliterData.map((item, index) => {
          return (
            <div
              className={classNames("item", {
                active: selectItem.includes(item),
              })}
              key={item}
              onClick={(e) => itemClick(item)}
            >
              {item}
            </div>
          )
        })}
      </div>
    </FilterWrapper>
  )
})

EntireFilter.propTypes = {}

export default EntireFilter
